/*
 * Copyright (c) 2006-2017, Yunnan Sanjiu Network technology Co., Ltd.
 * 
 * All rights reserved.
 */
package com.niguang.labour.common.config.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author ZhenJin
 */
public class NullJsonSerializer extends JsonSerializer<Object> {

    private JavaType clazz;

    public NullJsonSerializer(JavaType clazz) {
        this.clazz = clazz;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            if (clazz.isTypeOrSubTypeOf(String.class) || clazz.isTypeOrSubTypeOf(Date.class)
                    || clazz.isTypeOrSubTypeOf(LocalDateTime.class) || clazz.isTypeOrSubTypeOf(LocalDate.class)) {
                // String和时间处理为""
                gen.writeString("");
            } else if (clazz.isArrayType() || clazz.isTypeOrSubTypeOf(List.class) || clazz.isTypeOrSubTypeOf(Set.class)) {
                // 数组，list，set 处理为[]
                gen.writeStartArray();
                gen.writeEndArray();
            } else if (clazz.isTypeOrSubTypeOf(Number.class)) {
                // 数字类型处理为0
                gen.writeNumber(0);
            } else if (clazz.isTypeOrSubTypeOf(Boolean.class)) {
                // Boolean处理为false
                gen.writeBoolean(false);
            } else {
                // 其他空对象处理为 {}
                gen.writeStartObject();
                gen.writeEndObject();
            }
        } else {
            gen.writeObject(value);
        }
    }
}
